// mutexTest.c
//
// This program is a basic test of threads

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t count_mutex;
int count = 0;
int turn = 0;

void *start_thread_one()
{
  int i;
  for(i=1;i<5;i++) {
    while(turn!=0);
    pthread_mutex_lock(&count_mutex);
    count++;
    printf("thread one: %d\n",count);
    pthread_mutex_unlock(&count_mutex);
    turn = 1;
  }
  pthread_exit(0);
}

void *start_thread_two()
{
  int i;
  for(i=1;i<5;i++) {
    while(turn!=1);
    pthread_mutex_lock(&count_mutex);
    count--;
    printf("thread two: %d\n",count);
    pthread_mutex_unlock(&count_mutex);
    turn = 0;
  }
  pthread_exit(0);
}

int main()
{
  pthread_t p1, p2;
  
  pthread_create(&p1,NULL,(void *)start_thread_one,NULL);
  pthread_create(&p2,NULL,(void *)start_thread_two,NULL);
  
  pthread_join(p1,NULL);
  pthread_join(p2,NULL);
  
  return(0);
}
